#include "windows.h"
#include "main.h"
#include "TCHAR.h"

namespace cc
{
	MainApp::MainApp() : m_worker(NULL)
	{
		RunWorker();
	}

	MainApp::~MainApp()
	{
		if (m_worker)
		{
			SetWindowLong(m_worker,GWL_USERDATA,0);
			DestroyWindow(m_worker);
		}
	}

	static LRESULT CALLBACK WorkerWndProc(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam)
	{
		MainApp *w = (MainApp*)GetWindowLong(hWnd,GWL_USERDATA);
		switch(uMsg)
		{
		case WM_CREATE:
			{
				LPCREATESTRUCT pcs = (LPCREATESTRUCT)lParam;
				w = (MainApp *)pcs->lpCreateParams;
				w->m_worker = hWnd;
				SetWindowLong(hWnd,GWL_USERDATA,(LONG)w);
			}
			break;
		}

		if(w) w->ProcessMessage(hWnd,uMsg,wParam,lParam);
		return DefWindowProc(hWnd,uMsg,wParam,lParam);
	}

	void MainApp::RunWorker()
	{
		WNDCLASS wc;
		ZeroMemory(&wc,sizeof(wc));
		wc.cbClsExtra = 0;
		wc.cbWndExtra = 0;
		wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
		wc.hCursor = NULL;
		wc.hIcon = NULL;
		wc.hInstance = (HINSTANCE)GetModuleHandle(NULL);
		wc.lpfnWndProc = WorkerWndProc;
		wc.lpszClassName = TEXT("test");
		wc.lpszMenuName = 0;
		wc.style = CS_HREDRAW | CS_VREDRAW;

		RegisterClass(&wc);

		CreateWindow(TEXT("test"),TEXT("test"),WS_DISABLED,0,0,200,200,NULL,NULL,(HINSTANCE)GetModuleHandle(NULL),this);
		ShowWindow(m_worker,SW_SHOWNORMAL);
		UpdateWindow(m_worker);


		MSG msg;
		while(GetMessage(&msg,NULL,0,0))
		{
			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	LRESULT MainApp::ProcessMessage(HWND hWnd,UINT uMsg,WPARAM wParam, LPARAM lParam)
	{
		switch (uMsg)
		{
		case WM_CREATE: onCreate(); break;
		case WM_DESTROY:onDestroy(); break;
		default: 
			return DefWindowProc(hWnd,uMsg,wParam,lParam);
		}
		return 0;
	}

	void MainApp::onCreate()
	{
		MessageBox(m_worker,TEXT("run success!!!"),TEXT("test"),MB_OK);
	}

	void MainApp::onDestroy()
	{
		SetWindowLong(m_worker,GWL_USERDATA,0);
		DestroyWindow(m_worker);
		PostQuitMessage(0);
	}

}

void _tmain(int argc, _TCHAR* argv[])
{
	::cc::MainApp app;
}